package com.apply;

import java.util.Stack;

public class CheckParentheses {

    public static void main(String[] args) {
        String s = "{[(())]}";
        System.out.println(new CheckParentheses().isValid(s));
    }

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if ('{' == c || '[' == c || '(' == c) {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                char topChar = stack.pop();
                if ('}' == c && topChar != '{') {
                    return false;
                }
                if (']' == c && topChar != '[') {
                    return false;
                }
                if (')' == c && topChar != '(') {
                    return false;
                }
            }
        }
        // 最终判空很重要：只有栈中为空了才说明是匹配完成了
        return stack.isEmpty();
    }
}
